using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Gtk;
using NetworkCommsDotNet;

namespace JiveMessengerLinux
{
    [System.ComponentModel.ToolboxItem(true)]
    public partial class UserEmoticons : Gtk.Bin
    {
        private readonly Dictionary<string, string> _myEmoticons;
        private readonly Dictionary<string, string> _userEmoticon;
        private readonly string _customEmoticonFolder;
        private Gdk.Color ShortcutTakenColor { get; set; }
        private Gdk.Color ShortcutUsableColor { get; set; }

        public UserEmoticons(Dictionary<string, string> userEmoticons, Dictionary<string, string> myEmoticons, string customEmoticonFolder)
        {
            this.Build();
            Gdk.Color col = Gdk.Color.Zero;
            Gdk.Color.Parse("green", ref col);
            this.ShortcutTakenColor = col;
            Gdk.Color.Parse("white", ref col);
            this.ShortcutUsableColor = col;
            this._myEmoticons = myEmoticons;
            this._userEmoticon = userEmoticons;
            this._customEmoticonFolder = customEmoticonFolder;
            FillGrid();
        }

        private void FillGrid()
        {
            this.vbox4.Children.ToList().Clear();
            Dictionary<string, string> localUserEmoticon = new Dictionary<string, string>(this._userEmoticon);
            int row = 0;
            foreach (KeyValuePair<string, string> kvp in localUserEmoticon)
            {
                if (String.IsNullOrEmpty(kvp.Value) || String.IsNullOrEmpty(kvp.Key))
                    continue;
                string error;
                bool haveKey = !StaticMethods.ValidateEmoticonShortcut(kvp.Key, out error);


                string link = kvp.Value;

                HBox hBox = new HBox();

                Gtk.CheckButton cb = new CheckButton();
                cb.Sensitive = !haveKey;
                cb.Active = !haveKey;
                cb.Data.Add(kvp.Key, kvp.Value);
                cb.Data.Add(0, row);
                hBox.PackStart(cb, false, false, 0);

                Entry entry = new Entry(kvp.Key);
                entry.Data.Add(0, row);
                entry.TextInserted += new TextInsertedHandler(entry_TextInserted);
                entry.TextDeleted += new TextDeletedHandler(entry_TextDeleted);
                entry.WidthRequest = 80;
                if (haveKey)
                {
                    entry.ModifyBase(StateType.Normal, this.ShortcutTakenColor);
                }
                hBox.PackStart(entry, false, false, 0);

                Gtk.Image i = System.IO.Path.IsPathRooted(link) ? new Gtk.Image(link) : new Gtk.Image(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("JiveMessengerLinux.Resources." + link));
                i.Data.Add(0, row);
                hBox.PackStart(i, false, false, 0);
                row++;
                hBox.ShowAll();
                this.vbox4.PackStart(hBox, true, true, 0);
                this.vbox4.ShowAll();
            }
        }

        private void OnTextChanged(Entry entry)
        {
            Entry key = entry;
            if (key == null)
                return;
            string error;
            bool haveit = !StaticMethods.ValidateEmoticonShortcut(key.Text, out error);//MyEmoticons.ContainsKey(key.Text);
            if (!String.IsNullOrEmpty(error))
                key.TooltipText = error;
            //Gdk.Color shortcutTakenColor = Gdk.Color.Zero;
            //Gdk.Color.Parse("green", ref shortcutTakenColor);
            if (haveit)
                key.ModifyBase(StateType.Normal, this.ShortcutTakenColor);
            else
                key.ModifyBase(StateType.Normal, this.ShortcutUsableColor);
            // = haveit ? Brushes.Red : Brushes.White;
            CheckButton chk = GetEnabled((int)key.Data[0]);
            if (chk == null)
                return;

            chk.Active = !haveit;
            chk.Sensitive = !haveit;
        }

        private CheckButton GetEnabled(int row)
        {
            foreach (var va in this.vbox4.Children)
            {
                HBox hBox = va as HBox;
                if (hBox == null) return null;

                foreach (var v in hBox.Children)
                {
                    if (v.GetType() == typeof(CheckButton))
                    {
                        CheckButton bn = v as CheckButton;
                        if ((int)bn.Data[0] == row)
                        {
                            return bn;
                        }
                    }
                }
            }
            return null;
        }
        private Gtk.Image GetImage(int row)
        {
            foreach (var va in this.vbox4.Children)
            {
                HBox hBox = va as HBox;
                if (hBox == null) return null;

                foreach (var v in hBox.Children)
                {
                    if (v.GetType() == typeof(Image))
                    {
                        Image i = v as Image;
                        if ((int)i.Data[0] == row)
                        {
                            return i;
                        }
                    }
                }
            }
            return null;
        }
        private Entry GetEntry(int row)
        {
            foreach (var va in this.vbox4.Children)
            {
                HBox hBox = va as HBox;
                if (hBox == null) return null;

                foreach (var v in hBox.Children)
                {
                    if (v.GetType() == typeof(Entry))
                    {
                        Entry entry = v as Entry;
                        if ((int)entry.Data[0] == row)
                        {
                            return entry;
                        }
                    }
                }
            }
            return null;
        }
        private void entry_TextDeleted(object o, TextDeletedArgs args)
        {
            Entry entry = o as Entry;
            OnTextChanged(entry);
        }

        private void entry_TextInserted(object o, TextInsertedArgs args)
        {
            Entry entry = o as Entry;
            OnTextChanged(entry);
        }


        protected void OnBnAddUserEmoticonsClicked(object sender, EventArgs e)
        {
            if (this.vbox4.Children.Length == 0)
                return;
            //MemoryBox memoryBox = new MemoryBox(Window.GetWindow(this));
            bool ok = true;
            for (int i = 0; i < this.vbox4.Children.Length; i++)
            {
                HBox hBox = this.vbox4.Children[i] as HBox;

                bool? enabled = GetEnabled(i).Active;
                if (enabled.Value == false)
                    continue;
                Image emoticon = GetImage(i);
                String text = GetEntry(i).Text;
                string error;
                if (!StaticMethods.ValidateEmoticonShortcut(text, out error))
                {
                    MessageBox.Show(String.Format("Skipping {0}: {1}", text, error));
                    continue;
                }
                try
                {
                    FileInfo sourceFile = new FileInfo(emoticon.File);
                    string savePath = StaticMethods.CombinePath(this._customEmoticonFolder, sourceFile.Name);

                    if (File.Exists(savePath))
                    {
                        ok = false;


                        Gtk.MessageDialog md = new Gtk.MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, "Do you want to overwrite existing emoticons?: " + savePath);
                        md.Modal = true;
                        ResponseType result = (ResponseType)md.Run();
                        if (result == ResponseType.Yes)
                        {
                            ok = true;
                            ChatControl.NeedEmoticonRefresh = true;
                        }
                        md.Destroy();
                        //MemoryBoxResult result = memoryBox.ShowMemoryDialog("Do you want to overwrite this file?: " + savePath, "File exists");
                        //switch (result)
                        //{
                        //    case MemoryBoxResult.No:
                        //    case MemoryBoxResult.NoToAll:
                        //    case MemoryBoxResult.Cancel:
                        //        break;
                        //    case MemoryBoxResult.Yes:
                        //    case MemoryBoxResult.YesToAll:
                        //        ok = true;
                        //        break;
                        //}
                        //const MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                        //const MessageBoxImage icnMessageBox = MessageBoxImage.Warning;
                        //MessageBoxResult rsltMessageBox = MessageBox.Show("Do you want to overwrite this file?: " + savePath, "File exists", btnMessageBox, icnMessageBox);
                        //switch (rsltMessageBox)
                        //{
                        //    case MessageBoxResult.Yes:
                        //        {
                        //            ok = true;
                        //            break;
                        //        }
                        //    case MessageBoxResult.No:
                        //        break;
                        //}
                    }
                    if (ok)
                    {
                        File.Copy(emoticon.File, savePath,true);
                       // ImageManipulation.SaveImageData(ImageManipulation.GetEncodedImageData(emoticon.Source, ".gif"), savePath);
                        //ChatControl.CustomEmoticons.Add(text, savePath);
                    }
                    this._myEmoticons.Add(text, savePath);
                }
                catch (Exception err)
                {
                    NetworkComms.Logger.ErrorException("Error adding emoticon", err);
                    MessageBox.Show(err.Message);


                }
            }

          //  this.UserEmoticonsGrid.Children.Clear();
           // this.UserEmoticonsGrid.RowDefinitions.Clear();
            FillGrid();
        }
    }
}

